﻿using HtmlAgilityPack;
using Ozner.Common;
using Ozner.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Ozner.BLL
{
    public class LeftBLL : BaseBLL
    {
        public BaseResult<List<Menu>> GetMenuList(string url)
        {
            BaseResult<List<Menu>> br = GetLoginedDocument<List<Menu>>("/" + url);
            if(br.Code == Code.OK)
            {
                HtmlDocument doc = br.OtherInfo as HtmlDocument;
                //获取到所有的菜单
                HtmlNodeCollection hnDDs = doc.DocumentNode.SelectNodes("//dl[@class='leftmenu']/dd");
                if (hnDDs != null && hnDDs.Count > 0)
                {
                    List<Menu> menus = new List<Menu>();
                    //遍历hndds
                    foreach(HtmlNode hnDD in hnDDs)
                    {
                        //新建menu对象
                        Menu menu = new Menu();
                        //构建以dd为根的htmldocument
                        HtmlDocument docDD = new HtmlDocument();
                        docDD.LoadHtml(hnDD.OuterHtml);
                        //获取title节点
                        HtmlNode hnTitle = docDD.DocumentNode.SelectSingleNode("//div[@class='title']");
                        menu.Text = hnTitle == null ? "获取名称失败" : hnTitle.InnerText;
                        //获取子菜单元素
                        HtmlNodeCollection hnSons = docDD.DocumentNode.SelectNodes("//ul[@class='menuson']/li");
                        if (hnSons != null && hnSons.Count > 0)
                        {
                            //遍历子菜单元素
                            foreach(HtmlNode hnSon in hnSons)
                            {
                                Menu menuSon = new Menu();
                                //构建以hnSon为根的htmldocument
                                HtmlDocument docSon = new HtmlDocument();
                                docSon.LoadHtml(hnSon.OuterHtml);
                                //获取a标签元素
                                HtmlNode hnA = docSon.DocumentNode.SelectSingleNode("//a");
                                if (hnA != null)
                                {
                                    menuSon.Text = hnA.InnerText;
                                    menuSon.Href = hnA.Attributes["href"].Value;
                                }
                                menu.Menus.Add(menuSon);
                            }
                        }
                        menus.Add(menu);
                    }
                    br.Object = menus;
                    br.Code = Code.OK;
                }else
                {
                    br.Code = Code.NULL;
                    br.Message = "未获取到菜单信息!";
                }

            }
            return br;
        }
    }
}
